//tslint:disable
import { Component, OnInit, Input, NgZone } from '@angular/core';

import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { MessageService } from 'src/app/shared/service/message.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { EventService } from 'src/app/shared/service/event.service';
import { Subscription } from 'rxjs';
import { ActionSheetService } from 'ng-zorro-antd-mobile';
import { ModalController, ActionSheetController, AlertController } from '@ionic/angular';
import { ServiceModuleComponent } from '../service-module/service-module.component';
import { SharePageComponent } from '../share-page/share-page.component';
import { RemarksContentComponent } from '../remarks-content/remarks-content.component';
import { RecommendModalComponent } from '../recommend-modal/recommend-modal.component';
import { ModalFromCenterLeave, ModalFromCenterEnter } from 'src/app/utils/transitions';

@Component({
  selector: 'app-app-general-list',
  templateUrl: './app-general-list.component.html',
  styleUrls: ['./app-general-list.component.scss'],
})
export class AppGeneralListComponent implements OnInit {
  @Input() tagData: any;
  openRemarks = false;
  remarksText = "";
  remarksIcon: any;
  phoneArray = [];
  showLoadMore = false;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  tempEvent: any;
  // 筛选及页面数据参数
  params: any = { content: {} };
  sessionId: string;
  // 声明订阅对象
  subscription: Subscription = null;
  public refreshIds = new Set(); // 2024.10.16 refreshIds

  constructor(
    private ngZone: NgZone,
    private eventService: EventService,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private httpService: HttpService,
    private message: MessageService,
    private actionSheet: ActionSheetService, // 必须有
    public modalController: ModalController,
    private actionSheetCtrl: ActionSheetController,
    private alertController: AlertController,
  ) {
  }


  refreshListData(param) {
    const that = this;
    if (param === undefined) {
      return;
    } else if (param.type === 'ionRefresh') {
      this.refreshData(param);
      return;
    }
    this.pageNo = 1;
    this.params = { content: {} };
    this.params.content = param;
    this.params.id = this.tagData.data.submit.id;
    this.params.content.pageNo = this.pageNo;
    this.params.sessionId = localStorage.getItem("sessionId");
    this.httpService.post('application/submit', this.params, res => {
      if (res.success) {
        // if (res.data.submit) {
        //   this.params = res.submit; // 为了每次刷新下一页的参数 "oldIndex"
        // }
        this.tagData.data.data = [];
        const result = res.data.data; // JSON.parse(res.data.data);
        this.tagData.data.data = result;
        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        this.pageTotal = res.data.submit.content.pageTotal;

        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
      } else {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }

  ngOnInit() {
    const listenerName = this.tagData.name + 'AskForList';
    // 监听多选后的推荐
    if (this.eventService.eventEmit.listenerCount(listenerName) > 0) {
      this.eventService.eventEmit.removeListener(listenerName);
    }
    this.eventService.eventEmit.on(listenerName, (obj) => {
      this.refreshListData(obj);
    });
    // this.demoData();
    this.sessionId = localStorage.getItem('sessionId');
    if (this.tagData.data.submit !== undefined) {
      // 初始化参数
      this.params = this.tagData.data.submit;
      this.params.sessionId = this.sessionId;
      this.pageSize = this.tagData.pageSize;
      this.pageTotal = this.tagData.pageTotal;
      this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
    }

    if (!this.subscription && this.tagData.data.submit !== undefined) {
      // 获取筛选参数
      this.subscription = this.message.getMessage().subscribe(param => {
        if (this.tempEvent) {
          this.tempEvent.target.disabled = false;
        }

        if (param === undefined) {
          return;
        } else if (param.type === 'ionRefresh') {
          this.refreshData(param);
          return;
        }
        // // 重置当前页数
        this.pageNo = 1;
        this.params.content = param;
        // 页面数据参数
        this.params.content.pageNo = this.pageNo;
        // 请求获取新数据
        this.httpService.post('application/submit', this.params, res => {
          // 请求数据成功
          if (res.success) {
            const result = res.data.data; // JSON.parse(res.data.data);
            // 筛选数据
            this.tagData.data.data = result;

            this.pageTotal = res.data.submit.content.pageTotal;

            // tslint:disable-next-line:max-line-length
            this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
            setTimeout(() => {
              const currentPath = localStorage.getItem("tabPath");
              const mainSection = document.getElementById('home-app-coms-sec');
              if (result.length <= 2 && currentPath) {
                if (mainSection && currentPath !== null && currentPath === 'home/tab1') {

                  let totalHeight = 0;
                  // const scrollHeight = document.getElementById("scrollContent").scrollHeight;
                  if (document.getElementById("scrollContent")) {
                    totalHeight += document.getElementById("scrollContent").scrollHeight;
                  }
                  if (document.getElementById("home-data-map-entry-box")) {
                    totalHeight += document.getElementById("home-data-map-entry-box").clientHeight;
                  }

                  if (document.getElementById("myTabBar")) {
                    totalHeight += document.getElementById("myTabBar").clientHeight;
                  } else {
                    totalHeight += 49;
                  }
                  if (document.getElementsByClassName("superToolclass") && document.getElementsByClassName("superToolclass")[0]) {
                    totalHeight += document.getElementById("superToolclass")[0].clientHeight;
                  } else {
                    totalHeight += 44;
                  }
                  if (totalHeight > window.innerHeight) {
                    totalHeight = 500;
                  }
                  mainSection.style.height = 'calc(100vh - ' + totalHeight + 'px )';
                  mainSection.style.display = 'block';
                }
              } else {
                if (mainSection && currentPath !== null && currentPath === 'home/tab1') {
                  mainSection.style.height = '0px';
                  mainSection.style.display = 'none';
                }
              }

            }, 50);
          } else {
            // 请求数据失败
            this.appGlobalService.showToast(res.message, 2000, 'middle');
          }
        },
          err => {
            // 请求数据失败
            this.appGlobalService.showToast(err.message, 2000, 'middle');
          });
      });
    }
  }

  counselorCall(num) {
    this.httpService.changeCallNumber(num);
  }
  // 查看推荐
  seeRecommed(link) {
    this.appGlobalService.openPage(link);
  }
  goPage(item, event?) {
    if (event) {
      event.stopPropagation();
    }

    if (item.chat && item.chat.length > 0) {
      item['link'] = item.chat[0].link;
    }
    if (item.submit && item.link) {
      const params = {
        content: item.submit.params,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        // 请求数据成功
        if (res.success) {
          this.appGlobalService.openPage(item.link);
        } else {
          // 请求失败
          if (res.message) {
            this.appGlobalService.showToast(res.message, 2000, "middle");
          }
        }
      });
    } else if (item.link) {
      this.pageModalService.openPage(item.link);
    }
  }
  ngOnDestroy(): void {
    sessionStorage.removeItem('showName');
    if (this.tagData && this.refreshIds) {
      this.refreshIds.forEach(element => {
        this.eventService.removeCustomListListenersByName(element);
      });
    }
    if (this.tagData.data.submit !== undefined) {
      // 组件生命周期结束的时候，注销
      this.subscription.unsubscribe();
    }
  }
  refreshData(event) {
    this.params.sessionId = localStorage.getItem("sessionId");
    // 请求下一个页面
    this.pageNo = 1;
    this.params.content.pageNo = this.pageNo;
    // 请求获取新数据
    this.httpService.post("application/submit", this.params, res => {
      // 请求数据成功
      if (res.success) {

        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
          this.tagData.data.data = res.data.data;
          // this.cssStyle();

          // this.params = res.data.submit;
        } else {
          this.tagData.data.data = [];
          // 没有数据了
          // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
        }
        event.target.complete();
      } else {
        // 请求失败，更新当前页数
        this.tagData.data.data = [];
        this.pageNo = 1;
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
        event.target.complete();
      }
    });
  }

  loadMoreData(event) {
    try {
      this.tempEvent = event;
      // // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      // // 参数
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.httpService.post('application/submit', this.params, res => {

        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(v => {
              this.tagData.data.data.push(v);
            });
          } else {
            event.target.disabled = true;
          }
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
        event.target.complete();

      }, err => {
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, 'middle');
        event.target.complete();

      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }


  /**
   *
   * @param item 各种操作类型 icon 入口
   */
  iconClick(item, dataIndex) {
    // console.log(item);
    if (item.modelType === "iconLink") { // 聊天icon

      // 要先执行一个beforeSubmit，返回true再执行link
      if (item.beforeSubmit) {
        const params = {
          content: item.beforeSubmit.content,
          id: item.beforeSubmit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (res.success) {
            if (res.data && res.data.eventResult && item.link.params && item.link.params.eventResult) {
              item.link.params[item.link.params.eventResult] = res.data.eventResult;
            }
            this.iconLink(item);
          } else {
            this.appGlobalService.showToast(res.message, 1500, 'middle');
          }
        });
      } else {
        this.iconLink(item);
      }


    } else if (item.modelType === "iconSubmit") {
      // 领取
      const params = {
        // tslint:disable-next-line:max-line-length
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          // this.openInformation = false;
          // this.tagData.data.data[this.dataIndex] = res.data.data[0];
          if (item.link && item.link.target) {
            const pageParams = {
              pageId: item.link.target,
              params: item.link.params ? item.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }

          // 蜂喔商户1.6.17
          if (item.refresh !== undefined) {
            this.appGlobalService.reloadCurrentPage();
          }
        }
      });
    } else if (item.modelType === "phone") {
      // 要先执行一个beforeSubmit，返回true再执行link
      if (item.beforeSubmit) {
        const params = {
          content: item.beforeSubmit.content,
          id: item.beforeSubmit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (res.success) {
            this.phone(item);
          } else {
            this.appGlobalService.showToast(res.message, 1500, 'middle');
          }
        });
      } else {
        this.phone(item);
      }

    } else if (item.modelType === "dialog") {
      // 备注
      // this.remarksIcon = item;
      // this.openRemarks = true;
      this.presentModal("remarks", item);
    } else
      // 新增两个components类型
      if (item.modelType === "remarkList") {
        if (item.listRemark) {
          this.remarkList(item);
        }
      } else if (item.modelType === "serviceModal") {
        this.openSeviceModal("sevice-modal", item);
      } else if (item.modelType === "popupDiv") {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          this.pageModalService.getPageTagDataWithPageRes(res, data => {
            this.showRecommenMessage(data);
          });
        });
      } else if (item.modelType === "alertSubmit") {
        // 要先执行一个beforeSubmit，返回true再执行link
        if (item.beforeSubmit) {
          const params = {
            content: item.beforeSubmit.content,
            id: item.beforeSubmit.id,
            sessionId: localStorage.getItem("sessionId")
          };
          this.httpService.post("application/submit", params, res => {
            if (res.success) {
              this.alertSubmit(item, dataIndex);
            } else {
              this.appGlobalService.showToast(res.message, 1500, 'middle');
            }
          });
        } else {
          this.alertSubmit(item, dataIndex);
        }

      }
  }

  iconLink(item) {
    if (item.link.type && item.link.type === 'chat') {//收费
      if (item.link && item.link.params && item.link.params.user_id) {
        this.httpService.gotoChat(item, item.link.params.user_id);
      } else {
        // 新增需求打电话或者聊天前先submit
        this.httpService.gotoChat(item);
      }


    } else if (item.link.type && item.link.type === 'model') {
      // 未收费
      this.getVipData(item);
    } else if (item.link.type && item.link.type === 'page') {

      this.appGlobalService.openPage(item.link);
      // page页面 最后有submit 再执行submit
      if (item.submit) {
        const params = {
          content: item.submit.content,
          id: item.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
        });
      }

    } else if (item.label === '分享') {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, res => {
        console.log(JSON.parse(res.script));
        const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
        // console.log(tmpShareData);
        this.presentShareModal(tmpShareData);
      });
    } else {
      // 修改
      this.pageModalService.openPage(item.link);
    }
  }

  phone(item) {
    // 已收费
    if (item.link.type && item.link.type === 'phone') {

      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction(item);
      } else {
        this.presentAlertConfirm(this.phoneArray[0], item);
      }


    } else if (item.link.type && item.link.type === 'model') {
      // 未收费
      this.getVipData(item);

    } else {
      // 原列表电话逻辑
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction(item);
      } else {
        this.presentAlertConfirm(this.phoneArray[0], item);
      }
    }
  }
  alertSubmit(item, dataIndex?) {
    // 已收费
    if (item.link && item.link.type && item.link.type === 'page') {
      // page页面 最后有submit 再执行submit
      this.appGlobalService.openPage(item.link);
      if (item.submit) {
        const params = {
          content: item.submit.content,
          id: item.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
        });
      }
    } else if (item.link && item.link.type && item.link.type === 'model') {
      // 未收费
      this.getVipData(item);
    } else {
      // 原列表弹窗逻辑
      this.presentAlertSubmit(item, dataIndex);
    }
  }

  updateItem(link, dataIndex) {
    const params = {
      params: link.params,
      pageId: link.target,
      sessionId: localStorage.getItem("sessionId")
    };
    const that = this;
    if (that.tagData.data.data[dataIndex].updateItemType !== undefined
      && that.tagData.data.data[dataIndex].updateItemType === 'delete') {
      that.tagData.data.data.splice(dataIndex, 1);
      return;
    }
    this.httpService.post('application/page', params, async res => {
      const tagData = JSON.parse(res.script).views[0].tags;
      tagData.forEach(element => {
        if (element.style === 'appGeneralListTag' && element.data && element.data.data[0]) {
          that.tagData.data.data.splice(dataIndex, 1, element.data.data[0]);
        }

      });
    });
  }
  getVipData(item) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: item.link.target,
      params: item.link.params
    };
    this.httpService.post('application/page', params, res => {
      console.log(JSON.parse(res.script));
      const tmpData = JSON.parse(res.script).views[0].tags[0].data;
      this.showRecommenMessageVip(tmpData);
    });
  }
  // 切换搜索类别
  moreActionClick(obj) {
    this.eventService.eventEmit.emit('searchTabListener', obj);
  }

  async openSeviceModal(className, item) {
    const type = {
      "sevice-modal": ServiceModuleComponent,
    };
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: className,
      component: type[className],
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }


  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }

  async presentAction(item) {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[1], item);
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0], item);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }


  ngAfterViewInit(): void {
    let that = this;
    // 2023.12.08 是否存在刷新控件
    if (that.tagData
      && that.tagData.data
      && that.tagData.data.data
      && that.tagData.data.data.length > 0) {
      // 2023.12.08 配置了某个属性才检查是否有下拉刷新事件
      if (that.tagData.data.data[0].isShowRefresher === 'true') {
        const debouncedHandler = that.appGlobalService.debounce((data: any) => {
          if (that.tagData.refreshId !== undefined) {
            that.eventService.eventEmit.emit(that.tagData.refreshId, '1');
          }
        }, 300);
        that.eventService.eventEmit.on('checkListIsShowRefresher', debouncedHandler);
        if (that.tagData.refreshId !== undefined) {
          that.tagData.refreshId += 'a';
          that.refreshIds.add(that.tagData.refreshId);
          console.log('init list name success!', that.tagData.refreshId);
          const debouncedHandler2 = that.appGlobalService.debounce((data: any) => {
            let tempRefresher = true;
            if (tempRefresher) {
              tempRefresher = false;
              let tempParamsContent = {};
              if (!that.params) {
                that.params = { content: {} };
                if (that.tagData.data.submit.content) {
                  that.params.content = that.tagData.data.submit.content;
                }
              } else {
                if (that.params && that.params.content) {
                  tempParamsContent = JSON.parse(JSON.stringify(that.params.content));
                }
              }
              that.refreshListData(tempParamsContent);
              setTimeout(() => {
                tempRefresher = true; //防止2秒内重复请求
              }, 2000);
            }
          },300);
          that.eventService.eventEmit.on(that.tagData.refreshId, debouncedHandler2);
        }
      }
    }
  }



  async presentAlertConfirm(mobile, item?) {
    const msg = (item.label ? item.label + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);

            if (item && item.submit) { // 表示已联系
              const params = {
                content: item.submit.content,
                id: item.submit.id,
                sessionId: localStorage.getItem("sessionId")
              };
              this.httpService.post("application/submit", params, res => {

              });
            }
          }
        }
      ]
    });

    await alert.present();
  }

  /**
   * 提交备注
   */
  submitRemarks() {
    if (this.remarksText === "") {
      this.appGlobalService.showToast("请填写备注", 1000, "top");
      return;
    }
    const contentArray = this.remarksIcon.formData.button.submit.content;
    // tslint:disable-next-line:no-string-literal
    contentArray["remark_text"] = this.remarksText;
    const params = {
      content: contentArray,
      id: this.remarksIcon.formData.button.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        this.remarksText = "";
        this.openRemarks = false;
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      } else {
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      }
    });
  }

  async presentModal(value, item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { item, type: value }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
  }


  remarkList(more) {
    const that = this;
    const buttons: any = [];
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex);
          }, 200);
        }
      }
    );
  }

  selectItem(item, index) {
    const itemObj = item.listRemark[index];
    if (itemObj.modelType === 'dialog') {
      this.presentModal("remarks", itemObj);
    } else if (itemObj.modelType === 'iconLink') {
      // 修改 领取类型按钮
      const params = {
        pageId: itemObj.link.target,
        params: itemObj.link.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(params);
    } else if (itemObj.modelType === 'phone') {
      // 电话
      this.phoneArray = itemObj.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction(itemObj);
      } else {
        this.presentAlertConfirm(this.phoneArray[0], itemObj);
      }
    } else if (itemObj.modelType === 'iconSubmit') {
      // 领取
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.link.target) {
            const pageParams = {
              pageId: itemObj.link.target,
              params: itemObj.link.params ? itemObj.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    } else if (itemObj.modelType === 'popupDiv') {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, res => {
        this.pageModalService.getPageTagDataWithPageRes(res, data => {
          this.showRecommenMessage(data);
        });
      });
    } else if (itemObj.modelType === 'alertSubmit') {
      this.presentAlertSubmit(itemObj);
    }
  }
  // 购买信息 开通会员
  async showRecommenMessageVip(vipData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal-auto-heigth',
      component: RecommendModalComponent,
      componentProps: { vipData },
      leaveAnimation: ModalFromCenterLeave,
      enterAnimation: ModalFromCenterEnter

    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }
  // 推荐语
  async showRecommenMessage(tagData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      component: RecommendModalComponent,
      componentProps: { tagData },
      leaveAnimation: ModalFromCenterLeave,
      enterAnimation: ModalFromCenterEnter
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }

  // 二次确认短信
  async presentAlertSubmit(data, dataIndex?) {

    const alert = await this.alertController.create({
      header: data.label,
      message: data.alert,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            const params = {
              content: data.submit.content,
              id: data.submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.submit(params, data, dataIndex);
          }
        }
      ]
    });

    await alert.present();
  }

  submit(params, item?, dataIndex?) {
    this.httpService.post("application/submit", params, res => {
      if (res.message) {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      }
      if (item.refreshLink) {
        this.updateItem(item.refreshLink, dataIndex);
      }
      // del
      if (item.submit && item.submit.content && item.submit.content.needDel && dataIndex >= 0) {
        this.tagData.data.data.splice(dataIndex, 1);
      }

      // 邀约
      if (params.content && params.content.way === "4") {
        if (res.data && res.data.eventResult && res.data.eventResult.indexOf("#") > -1) {
          const msg = res.data.eventResult.split("#")[0];
          this.appGlobalService.showToast(msg, 1500, "middle");

          const paramsString = res.data.eventResult.split("#")[1];
          // tslint:disable-next-line:prefer-const
          let params: any = {};
          const paramArray = paramsString.split(",");
          // tslint:disable-next-line:prefer-for-of
          for (let i = 0; i < paramArray.length; i++) {
            const p = paramArray[i].split(":");
            params[p[0]] = p[1];
          }
          this.sendInvitationMsg(params);
        }
      }
    });
  }
  sendInvitationMsg(params) {
    if (localStorage.getItem('userId') !== 'null') {
      if (params.opportunity_id) {
        const tmpMsgBody = {
          auth: true,
          opportunity_id: params.opportunity_id,
          imags: params.imags,
          pluginId: params.pluginId,
          title: params.title,
          big_district: params.big_district ? params.big_district : '',
          district: params.district ? params.district : '',
          area: params.area ? params.area : '',
          industry: params.industry ? params.industry : '',
          rentunit: params.rentunit ? params.rentunit : '元/月',
          rent: params.rent ? params.rent : '',
          transfer_fee: params.transfer_fee ? params.transfer_fee : '',
          from: localStorage.getItem("connUserId"),
          type: "opp"
        };
        // params.opportunity_id  params.current_opportunity_id
        // tslint:disable-next-line:max-line-length
        this.httpService.getImIdForInviteMsg(JSON.stringify(tmpMsgBody), params.opportunity_id, params.current_opportunity_id, (resItem) => {
          localStorage.removeItem('needRefresh');
          localStorage.setItem('onSendWebSocketMessageTag', 'true');
          const nowDate = Date.now();
          const message = {
            text: params.title,
            toId: resItem.toId,
            fromId: localStorage.getItem("connUserId"),
            key: resItem.id,
            type: 'opp',
            rentunit: params.rentunit ? params.rentunit : '元/月',
            opportunity_id: params.opportunity_id,
            // tslint:disable-next-line:max-line-length
            title: params.title,
            imags: params.imags,
            pluginId: params.pluginId,
            big_district: params.big_district ? params.big_district : '',
            district: params.district ? params.district : '',
            area: params.area ? params.area : '',
            industry: params.industry ? params.industry : '',
            rent: params.rent ? params.rent : '',
            transfer_fee: params.transfer_fee ? params.transfer_fee : '',
            nowDate
          };
          this.eventService.eventEmit.emit("onSendWebSocketMessage", message);
        });

      }


      // // 发送商机信息
      // if (params.customId) {
      //   this.httpService.getImId(params.opportunity_id, undefined, positionInfo.code ? positionInfo.code : 4403, (resItem) => {
      //     localStorage.removeItem('needRefresh');
      //     localStorage.setItem('onSendWebSocketMessageTag', 'true');
      //     const nowDate = Date.now();
      //     const message = {
      //       text: params.title,
      //       toId: resItem.toId,
      //       fromId: localStorage.getItem("connUserId"),
      //       key: resItem.id,
      //       type: 'opp',
      //       rentunit: resItem.rentunit ? resItem.rentunit : '元/月',
      //       opportunity_id: params.opportunity_id,
      //       // tslint:disable-next-line:max-line-length
      //       title: params.title,
      //       imags: params.imags,
      //       pluginId: params.pluginId,
      //       big_district: params.big_district ? params.big_district : '',
      //       district: params.district ? params.district : '',
      //       area: params.area ? params.area : '',
      //       industry: params.industry ? params.industry : '',
      //       rent: params.rent ? params.rent : '',
      //       transfer_fee: params.transfer_fee ? params.transfer_fee : '',
      //       nowDate
      //     };
      //     this.eventService.eventEmit.emit("onSendWebSocketMessage", message);
      //   });
      // } else {
      //   // 客户未注册的话 记录消息

      // }
    }
  }

  demoData() {
    // this.tagData = {
    //   type: "tag",
    //   style: "headerTotalTag",
    //   name: "headerTotalTag",
    //   linearLayout: "header",
    //   cssStyle: "height: 4.32rem;background: #F7F8FA;",
    //   data: [

    //       {
    //         label:'', 
    //         value:'合计',
    //         valueCssStyle:"background: #27282E;border-radius: 0.57rem;height: 1rem; line-height:1rem",
    //         cssStyle:"flex-basis:4rem;"
    //       },
    //       {
    //         label:'单量',
    //         value:'10',
    //         valueCssStyle:"font-size: 1.38rem;font-weight: bold;color: #27282E;",
    //         cssStyle:"flex-glow:1;"
    //       },
    //       {
    //         label:'业绩',
    //         value:'<font size=0.75rem>￥</font>130000',
    //         valueCssStyle:"font-size: 1.38rem;font-weight: bold;color: #27282E;",
    //         cssStyle:"flex-basis:10rem;"
    //       } 
    //   ]
    // };




    this.tagData = {
      type: "tag",
      style: "appGeneralListTag",
      name: "appGeneralListTag",
      linearLayout: "body",
      data: {
        isMargin: false,
        itemCssStyle: "background:rgba(255,255,255,1);box-shadow:0rem 0.25rem 0.63rem 0rem rgba(39,40,46,0.05); border-radius:0.31rem; border:0.03rem solid rgba(235,235,237,1);",
        data: [
          {
            plugin_id: "-1",
            downTag: {
              phone: {
                icon: "call-big@3x.png",
                text: "18378082631"
              },
              icon: "call-big@3x.png",
              name: "秋晓萌",
              label: {
                firstText: "成功服务",
                secondText: "635",
                thirdText: "位客户"
              }
            },
            title: "信息不好找?",
            content: "立即联系找店顾问，为您整理推荐合适客户"
          },
          {
            area: "100-180m²",
            plugin_id: "3",
            recommedBox: {
              firstText: {
                label: "共为该客户推荐"
              },
              secondText: {
                cssStyle: "....",
                label: "98"
              },
              lookLink: {
                label: "查看",
                icon: "..../png",
                link: {
                  type: "page",
                  params: {
                    opportunity_id: "5f22393cbd216a00010ca013",
                    customer_id: "5eb3e1dcd46ee000016397a3"
                  },
                  target: "145408"
                }
              },
              thirdText: {
                label: "位选址客户"
              }
            },
            downleft: {
              firstText: {
                cssStyle: "这里填样式",
                label: "跟进中"
              }
            },
            consultantBox: {
              firstRowLeft: {
                firstText: {
                  label: "实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求"
                }
              },
              headRowLeft: {
                firstText: {
                  label: "顾问秋小萌"
                },
                secondText: {
                  label: "推荐人"
                },
                icon: {
                  iconName: ""
                }
              }
            },
            downRight: {
              iconList: [
                {
                  iconName: "list_operation_icon_deal@3x.png",
                  phone: "18378082631",
                  modelType: "phone",
                  label: "打电话"
                },
                {
                  iconName: "list_operation_icon_deal@3x.png",
                  modelType: "chat",
                  label: "聊天"
                },
                {
                  submit: {
                    id: "2393db81-4696-4eae-ba3b-eb5d484a56b7",
                    content: {
                      opportunity_id: "5f22393cbd216a00010ca013"
                    }
                  },
                  iconName: "list_operation_icon_send@3x.png",
                  alert: "您确定要邀约来店铺考考察洽谈吗？",
                  modelType: "alertSubmit",
                  label: "邀约"
                }
              ]
            },
            time: "5分钟前",
            title: {
              leftAuthSign: {
                cssStyle: "这里写样式",
                label: "认证"
              },
              fistText: {
                label: "先生找南山区美甲店"
              }
            }
          },
          { //////////
            plugin_id: "1",
            img: {
              imgUrl: "http://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_8f4c788fceec915b28db630ed434d375.jpg",
              authSign: {
                cssStyle: "color:white",
                label: "认证"
              }
            },
            recommedBox: {
              // new add
              icon: 'list_icon_recommend@3x.png',
              firstText: {
                label: "共为该客户推荐"
              },
              secondText: {
                cssStyle: "....",
                label: "98"
              },
              lookLink: {
                label: "查看",
                icon: "..../png",
                link: {
                  type: "page",
                  params: {
                    opportunity_id: "5ec62fd8d8573400019550ba",
                    customer_id: "5eb3e1dcd46ee000016397a3"
                  },
                  target: "145408"
                }
              },
              thirdText: {
                label: "位选址客户"
              }
            },
            downleft: {
              firstText: {
                cssStyle: "这里填样式",
                label: "跟进中"
              }
            },
            "consultantRemark": { //consultantBox 不同时出现
              "firstRowLeft": {
                "firstText": {
                  "label": "实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求"
                }
              },
              "headRowLeft": "顾问导语："
            },
            consultantBox: {
              firstRowLeft: {
                firstText: {
                  label: "实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求"
                }
              },
              headRowLeft: {
                firstText: {
                  label: "顾问秋小萌"
                },
                secondText: {
                  label: "推荐人"
                },
                icon: {
                  iconName: ""
                }
              }
            },
            downRight: {
              iconList: [
                {
                  iconName: "expert_icon_chat_big@3x.png",
                  phone: "18378082631",
                  modelType: "phone",
                  label: "打电话",
                  tip: "邀约"
                },
                {
                  iconName: "expert_icon_chat_big@3x.png",
                  modelType: "chat",
                  label: "聊天",
                  tip: "聊天"
                },
                {
                  submit: {
                    id: "2393db81-4696-4eae-ba3b-eb5d484a56b7",
                    content: {
                      opportunity_id: "5ec62fd8d8573400019550ba"
                    }
                  },
                  iconName: "expert_icon_chat_big@3x.png",
                  alert: "您确定要邀约来店铺考考察洽谈吗？",
                  modelType: "alertSubmit",
                  label: "邀约",
                  tip: "邀约"
                }
              ]
            },
            transferFee: "转让费25万",
            time: "5分钟前",
            title: {
              fistText: {
                label: "转让 | 福田区八卦岭餐馆"
              }
            },
            rent: "9000元/月"
          },
          {
            plugin_id: "9",
            img: {
              imgUrl: "https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_a017c61d2bce454f9b9564ca8cb2a379.png",
              authSign: {
                cssStyle: "color:red;",
                label: "认证"
              }
            },
            recommedBox: {

              firstText: {
                label: "共为该客户推荐"
              },
              secondText: {
                cssStyle: "....",
                label: "98"
              },
              LookLink: {
                label: "查看",
                icon: "..../png",
                link: {
                  type: "page",
                  params: {
                    opportunity_id: "5eb3e1dcd46ee000016397a4",
                    customer_id: "5eb3e1dcd46ee000016397a3"
                  },
                  target: "145408"
                }
              },
              thirdText: {
                label: "位选址客户"
              }
            },
            downleft: {
              firstText: {
                cssStyle: "这里填样式",
                label: "跟进中"
              }
            },
            avgPrice: {
              firstText: {
                label: "均价"
              },
              secondText: {
                label: "5-9万"
              }
            },
            consultantBox: {
              firstRowLeft: {
                firstText: {
                  label: "实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求"
                }
              },
              headRowLeft: {
                firstText: {
                  label: "顾问秋小萌"
                },
                secondText: {
                  label: "推荐人"
                },
                icon: {
                  iconName: ""
                }
              }
            },
            downRight: {
              iconList: [
                {
                  iconName: "list_operation_icon_deal@3x.png",
                  phone: "18378082631",
                  modelType: "phone",
                  label: "打电话"
                },
                {
                  iconName: "list_operation_icon_deal@3x.png",
                  modelType: "chat",
                  label: "聊天"
                },
                {
                  submit: {
                    id: "2393db81-4696-4eae-ba3b-eb5d484a56b7",
                    content: {
                      opportunity_id: "5eb3e1dcd46ee000016397a4"
                    }
                  },
                  iconName: "list_operation_icon_send@3x.png",
                  alert: "您确定要邀约来店铺考考察洽谈吗？",
                  modelType: "alertSubmit",
                  label: "邀约"
                }
              ]
            },
            industry: "餐饮美食",
            title: {
              rightAuthSign: {
                cssStyle: "color:red",
                label: "认证"
              },
              fistText: {
                label: "尚泰装饰设计"
              }
            },
            labels: ['国家一级资质', '免费上门', '签订合同', '无转包']
          },
          {
            area: "100-180m²",
            plugin_id: "4",
            img: {
              imgUrl: "https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_ddf2af53ae037d7eb4208f9d03bfb040.png;https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_d5266dcc2cf9d4c072bde7b18fb5d6f1.jpg",
              authSign: {
                cssStyle: "这里写样式",
                label: "认证"
              }
            },
            recommedBox: {
              firstText: {
                label: "共为该客户推荐"
              },
              secondText: {
                cssStyle: "....",
                label: "98"
              },
              LookLink: {
                label: "查看",
                icon: "..../png",
                link: {
                  type: "page",
                  params: {
                    opportunity_id: "5ebb59944673ef0001b383a5",
                    customer_id: "5eb3e1dcd46ee000016397a3"
                  },
                  target: "145408"
                }
              },
              thirdText: {
                label: "位选址客户"
              }
            },
            downleft: {
              firstText: {
                cssStyle: "这里填样式",
                label: "跟进中"
              }
            },
            consultantBox: {
              firstRowLeft: {
                firstText: {
                  label: "实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求"
                }
              },
              headRowLeft: {
                firstText: {
                  label: "顾问秋小萌"
                },
                secondText: {
                  label: "推荐人"
                },
                icon: {
                  iconName: ""
                }
              }
            },
            downRight: {
              iconList: [
                {
                  iconName: "list_operation_icon_deal@3x.png",
                  phone: "18378082631",
                  modelType: "phone",
                  label: "打电话"
                },
                {
                  iconName: "list_operation_icon_deal@3x.png",
                  modelType: "chat",
                  label: "聊天"
                },
                {
                  submit: {
                    id: "2393db81-4696-4eae-ba3b-eb5d484a56b7",
                    content: {
                      opportunity_id: "5ebb59944673ef0001b383a5"
                    }
                  },
                  iconName: "list_operation_icon_send@3x.png",
                  alert: "您确定要邀约来店铺考考察洽谈吗？",
                  modelType: "alertSubmit",
                  label: "邀约"
                }
              ]
            },
            time: "5分钟前",
            title: {
              fistText: {
                label: "小明的物业火热招租中"
              }
            },
            rent: "1111000-10000元/月"
          },
          {
            plugin_id: "6",
            img: {
              imgUrl: "http://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_d5266dcc2cf9d4c072bde7b18fb5d6f1.jpg",
              authSign: {
                cssStyle: "这里写样式",
                label: "认证"
              }
            },
            recommedBox: {
              firstText: {
                label: "共为该客户推荐"
              },
              secondText: {
                cssStyle: "....",
                label: "98"
              },
              lookLink: {
                label: "查看",
                icon: "..../png",
                link: {
                  type: "page",
                  params: {
                    opportunity_id: "5ebc9a9dd97b18000159efd4",
                    customer_id: "5eb3e1dcd46ee000016397a3"
                  },
                  target: "145408"
                }
              },
              thirdText: {
                label: "位选址客户"
              }
            },
            downleft: {
              firstText: {
                cssStyle: "这里填样式",
                label: "跟进中"
              }
            },
            avgPrice: {
              secondText: {
                label: "5-9万"
              }
            },
            intro: "李家有米用李家有米用李家有米用李家有米用。",
            consultantBox: {
              firstRowLeft: {
                firstText: {
                  label: "实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求实地考察，符合选址要求"
                }
              },
              headRowLeft: {
                firstText: {
                  label: "顾问秋小萌"
                },
                secondText: {
                  label: "推荐人"
                },
                icon: {
                  iconName: ""
                }
              }
            },
            downRight: {
              iconList: [
                {
                  iconName: "list_operation_icon_deal@3x.png",
                  phone: "18378082631",
                  modelType: "phone",
                  label: "打电话"
                },
                {
                  iconName: "list_operation_icon_deal@3x.png",
                  modelType: "chat",
                  label: "聊天"
                },
                {
                  submit: {
                    id: "2393db81-4696-4eae-ba3b-eb5d484a56b7",
                    content: {
                      opportunity_id: "5ebc9a9dd97b18000159efd4"
                    }
                  },
                  iconName: "list_operation_icon_send@3x.png",
                  alert: "您确定要邀约来店铺考考察洽谈吗？",
                  modelType: "alertSubmit",
                  label: "邀约"
                }
              ]
            },
            industry: "餐饮美食",
            title: {
              cooperationSign: {
                cssStyle: "这里写样式",
                label: "合作品牌"
              },
              fistText: {
                label: "衣服很好，设计很棒"
              }
            }
          }
        ],
        submit: {
          content: {
            contract_plugin_id: "1",
            pageNo: 1
          },
          id: "420a7f4a-e26f-4b75-a79a-9d9a4705fb62"
        }
      },
      moreButton: {
        link: {
          type: "page",
          params: {
            opportunity_id: "11111"
          },
          target: "145397"
        },
        label: "查看更多"
      },
      pageSize: 10,
      pageNo: 1,
      pageTotal: 6
    };
  }
}
